function updateAll() {
  for (var i = 0; i < servers.length; ++i) {
    try {
      servers[i].authenticate();
    } catch (e) {}
  }
}

function updateBadge() {
  var disabled = 0;
  var failing = 0;
  var passing = 0;
  for (var s = 0; s < servers.length; ++s) {
    for (var p = 0; p < servers[s].plans.length; ++p) {
      var plan = servers[s].plans[p];
      if (plan.ignored === PlanStatus.IGNORED) {
        continue;
      } else if (plan.disabled !== PlanStatus.ENABLED) {
        ++disabled;
      } else if (plan.passing === PlanStatus.FAILING) {
        ++failing;
      } else {
        ++passing;
      }
    }
  }
  if (failing > 0) {
    setBadge(PlanStatus.FAILING, failing);
  } else if (disabled > 0) {
    setBadge(PlanStatus.DISABLED);
  } else if (passing > 0) {
    setBadge(PlanStatus.PASSING);
  } else {
    setBadge();
  }
}

//status : Passing, count : int
function setBadge(status, count) {
  switch (status) {
    case PlanStatus.FAILING:
      var color = [255, 0, 0, 255];
      var badgeText = count + "";
      break;
    case PlanStatus.DISABLED:
      var color = [0xCC, 0xCC, 0xCC, 255];
      var badgeText = "D";
      break;
    case PlanStatus.PASSING:
      var color = [0, 255, 0, 200];
      var badgeText = "OK";
      break;
    default:
      var color = [0, 0, 0, 0];
      var badgeText = "";
  }
  chrome.browserAction.setBadgeText({text: badgeText});
  chrome.browserAction.setBadgeBackgroundColor({color: color});
  localStorage["servers"] = JSON.stringify(servers);
  var views = chrome.extension.getViews({type: "popup"});
  for (var v = 0; v < views.length; ++v) {
    views[v].load();
  }
}

function updateServerDetailsFromLocalStorage() {
  getServerDetailsFromLocalStorage();
  update();
}

function update() {
  updateAll();
  setTimeout(update, updateInterval * 60000);
}

function notifyOfFailure(planName, server) {
  var link = server.scheme + "://" + server.host + "/browse/" + planName + "/latest";
  webkitNotifications.createHTMLNotification("notification.html?planName=" + planName + "&link=" + link).show();
}

if (localStorage["version"] === undefined || localStorage["version"] === "0.0.1") {
  chrome.tabs.create({url: chrome.extension.getURL("options.html"), selected: true});
}

localStorage["version"] = "0.0.11";

updateServerDetailsFromLocalStorage();